#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

enum{
    USERAGEFAILD = -1,
    OPENFAILD    =-2,
    READFAILD    = -3,
    WRITEFAILD   = -4
};
void Userage(void)
{
    printf("./process filename num");
    
}
static char readbuf[100];
static char writebuf[100];
static const char data[] = "hello world\n\r";

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Userage();
        return USERAGEFAILD;
    }
    char *filename = argv[1];
    //打开文件
    int fd;
    fd = open(filename, O_RDWR);
    if (fd < 0)
    {
        printf("open file failed \r\n");
        return OPENFAILD;
    }
    if (atoi(argv[2]) == 1)
    {
        //读出数据
        int retvalue;
        retvalue = read(fd,readbuf, sizeof(readbuf - 1));
        if (retvalue < 0)
        {
            printf("read faild\n\r");
            return READFAILD;
        }
        printf("read data  :  %s", filename);
    }
    if (atoi(argv[2]) == 2)
    {
        //写入数据
        memcpy(writebuf, data, sizeof(data));
        int retval;
         retval = write(fd, writebuf, sizeof(writebuf));
        if (retval < 0)
        {
            printf("write faild\n\r");
            return WRITEFAILD;
        }
        printf("write sucess  %s", filename);
    }
    //关闭文件
    printf("close file\n\r");
    close(fd);
    return 0;
}